<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../day48/demo/js/ajax.js"></script>
    <style>
        div {
            user-select: none;
        }

        .right {
            font-size: 12px;
            color: green;
        }

        .err {
            font-size: 12px;
            color: red;
        }
    </style>
</head>
<body>
    <form onsubmit="return false">
        <p>
            <label for="user">用户名:</label>
            <input type="text" id="user" placeholder="用户名">
            <span id="user_span"></span>
        </p>

        <p>
            <input type="submit" id="btn" value="注册">
        </p>
    </form>
</body>
<script>
    var userInp = document.getElementById("user");
    var userSpan = document.getElementById("user_span");

    userInp.onblur = function(){
        var user = userInp.value.trim();
        userInp.value = user;
        isUserOk = false;

        var reg = /^[a-zA-Z_]\w{5,11}$/;

        if(reg.test(user)){
            var p = isExistUser({ user });
            console.log(p);
            p.then(function(msg){
                userSpan.textContent = "√";
                userSpan.className = "right";
                isUserOk = true;
            },function(msg){
                userSpan.textContent = msg;
                userSpan.className = "err";
            })
        }else{
            userSpan.textContent = "用户名由数字、字母、下划线组成,6-12位,且不能以数字开头";
            userSpan.className = "err";
        }
    }

    function isExistUser(params){
        var p = new Promise(function(resolve,reject){
            $.ajax({
                type:"get",
                url:"../day48/demo/php/isExistUser.php",
                data:{
                    ...params
                },
                dataType: "json",
                success: function(result){
                    var { status, msg } = result;
                    if(status){
                        resolve(msg);
                    }else{
                        reject(msg);
                    }
                    console.log(p);
                }
            })
        })
        return p;
    }
</script>
</html>